﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TI_BAL;
using DevEck.Devices.Video;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


namespace SecuritySystem
{
    public partial class AddEditUser : Form
    {
        #region Data Variables

        TIEntities dbContext;
        bool isFormSaved = false;
        string photoPath = "";
        private InputLanguage UrduLanguage;
        private InputLanguage EnglishLanguage;
        byte[] globalPhoto = null;
       // int globalEditVariable = -1;
        public DataGridViewRow selectedRecord = null;
        Byte[] thumbImpression = null;

        #endregion

        #region Constructor

        public AddEditUser()
        {
            InitializeComponent();
            dbContext = new TIEntities();
         //   globalEditVariable = 9; // Loading Gloabal Varbiale
        }
        
        #endregion

        #region Control Events
             

        private void AddEditUser_Load(object sender, EventArgs e)
        {

            if (selectedRecord == null)
            {
                RefreshForm();
            }
            else
            {
                this.buttonNewCard.Enabled = true;
                LoadForm();
            }   
        }             

      
        private void buttonCaptureImage_Click(object sender, EventArgs e)
        {
            
                //SaveFileDialog saveFileDlg = new SaveFileDialog();
            
                Bitmap captureImage = imageCaptureControlCamera.Capture();
            
                
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                

                Image imageToSave = (Image)captureImage;
                imageToSave = Utility.ResizeImage(imageToSave, new Size(244,288));
                imageToSave.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                imageToSave.Save(@"C:\TechxionDB\Photos\user.jpg", ImageFormat.Jpeg);

                //this.pictureBoxProfilePic.Image = Image.FromFile(@"C:\TechxionDB\Photos\user.jpg");

                stream.Position = 0;
                globalPhoto = stream.GetBuffer();



                MemoryStream ms = new MemoryStream(globalPhoto);

                Bitmap img = (Bitmap)Image.FromStream(ms);

                //img.Save(@"C:\TechxionDB\Photos\user.jpg", ImageFormat.Jpeg);

                this.pictureBoxProfilePic.Image = (Image)img;


            
        }
            

        private void AddEditUser_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                this.imageCaptureControlCamera.Stop();
                this.imageCaptureControlCamera.Device = null;
            }
            catch (Exception ex)
            { }
            //this.imageCaptureControlCamera.Dispose();

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }

        private SecurityUser instentiateUserObject()
        {
            if (selectedRecord == null)
            {
                return  new SecurityUser();
            }
            else
            {
                int id = int.Parse(selectedRecord.Cells["id"].Value.ToString());
                return  (from s in dbContext.SecurityUsers where s.id == id select s).FirstOrDefault();
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {

            /******Enter User Profile*******/
           
                try
                {
                    TI_BAL.SecurityUser user = instentiateUserObject();

                    if (selectedRecord == null && thumbImpression == null)
                    {
                        MessageBox.Show("Thumb Impression is neccessary");
                        return;
                    }
                    
                    //if (selectedRecord != null)
                    //{
                    //    int userId = int.Parse(selectedRecord.Cells["UserId"].Value.ToString().Trim());
                    //    // TIEntities dbContext;
                    //    var ctx = new TIEntities();


                    //    var delGurantor = (from guran in ctx.Gurantors
                    //                       where guran.UserID == userId
                    //                       select guran);
                    //    ctx.DeleteObject(delGurantor);

                    //    ctx.SaveChanges();

                    //}
                    
                    
                    user.UserId = this.textBoxID.Text.Trim();
                    user.Name = this.textBoxName.Text.Trim();
                    user.FatherName = this.textBoxFatherName.Text.Trim();
                    user.NIC = this.maskedTextBoxNIC.Text.Trim();
                    user.PhoneNumber = this.textBoxPhoneNumber.Text.Trim();

                    user.PermAddress = this.textBoxAddress.Text.Trim();
                    user.PresenAddress = this.textBoxPresentAddress.Text.Trim();
                    user.RoleId = Convert.ToInt32(this.comBoxRole.SelectedValue.ToString());
                    user.RoleDesId = Convert.ToInt32(comBoxRoleDesc.SelectedValue.ToString());
                    user.OtherDesc = textBoxOtherDetails.Text.Trim();

                    user.DOB = this.dateTimePickerDOB.Value;
                    user.DOE = this.dateTimePickerExpiry.Value;


                    user.IsActive = this.checkBoxActive.Checked;


                    user.MembershipId = this.textBoxMembership.Text.Trim();

                    
                    user.Photo = globalPhoto;

                    Image thumbImg = Image.FromFile(@"C:\TechxionDB\Photos\thumb.jpg");

                    MemoryStream msThumb = new MemoryStream();
                    

                    if (globalPhoto == null) // set thumb as photo
                    {
                        user.Photo = msThumb.ToArray();
                        thumbImg.Save(@"C:\TechxionDB\Photos\user.jpg");
                    }

                    if (selectedRecord == null)
                    {
                        dbContext.AddToSecurityUsers(user);
                    }

                    user.ThumbImage = msThumb.ToArray();
                    user.ThumbBytes = thumbImpression;

                    dbContext.SaveChanges();

                    foreach (DataGridViewRow r in dGV.Rows)
                    {
                  
                        fillRoleGrid(user.id, int.Parse(r.Cells[2].Value.ToString()),
                        int.Parse(r.Cells[4].Value.ToString()), int.Parse(r.Cells[0].Value.ToString()));

                    }

                    this.barcode1.DataToEncode = "TECH" + this.textBoxID.Text.Trim();
                    this.barcode1.BMPPicture.Save(@"C:\TechxionDB\Photos\BarCode.jpg", ImageFormat.Jpeg);

                    MessageBox.Show("کامیاب اندراج ہو گیا ہے۔");
                   
                    //this.Close();
                    this.buttonPrint.Enabled = true;
                    this.buttonSave.Enabled = false;

                    

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Some Error Occured");
                }

           
            

            
            //this.Close();
        }

        private void fillRoleGrid(int UserId, int rollId, int rollDesId, int gurId )
        {

            TI_BAL.Gurantor gra = new Gurantor();
            TIEntities dbRoleContext = new TIEntities();


           
           
                gra.UserID = UserId;
                gra.RoleID = rollId;
                gra.RoleDesID = rollDesId;
                gra.GurantorID = gurId;

                dbRoleContext.Gurantors.AddObject(gra);
           

            dbRoleContext.SaveChanges();
        }
        private void dateTimePickerDOB_ValueChanged(object sender, EventArgs e)
        {
            this.dateTimePickerExpiry.Value = this.dateTimePickerDOB.Value.AddYears(1);
        }


        private void textBoxInputUrduLanguage_Enter(object sender, EventArgs e)
        {
            InputLanguage.CurrentInputLanguage = UrduLanguage;
        }

        private void textBoxInputEnglishLanguage_Enter(object sender, EventArgs e)
        {
            InputLanguage.CurrentInputLanguage = EnglishLanguage;
        }

        #endregion

        #region Data Methods
        private void RefreshForm()
        {
            AssignLanguage();
            this.textBoxID.Text = generatID().ToString();
            this.textBoxName.Text = "";
            this.textBoxAddress.Text = "";
            this.textBoxPresentAddress.Text = "";
            this.textBoxPhoneNumber.Text = "";
            this.checkBoxActive.Checked = false;
            this.dateTimePickerDOB.Value = DateTime.Today;
            this.dateTimePickerExpiry.Value = DateTime.Today.AddMonths(6);
            this.maskedTextBoxNIC.Text = "";
            //this.comboBoxRole.DataSource = "";
           // this.comboBoxRole.DataBindings();
            var userRole = (from uRole in dbContext.Roles
                            select new {ID = uRole.id, ROLE = uRole.role1 }).ToList();
            this.comBoxRole.DataSource = userRole; //new BindingSource(getRoles(), null);
            this.comBoxRole.DisplayMember = "ROLE";
            this.comBoxRole.ValueMember = "ID";

            var userRoleDes = (from uRole in dbContext.RolesDescriptions
                            select new { ID = uRole.ID, ROLEDES = uRole.Role_Description }).ToList();
            this.comBoxRoleDesc.DataSource = userRoleDes; //new BindingSource(getRoles(), null);
            this.comBoxRoleDesc.DisplayMember = "ROLEDES";
            this.comBoxRoleDesc.ValueMember = "ID";


            var userRoleG = (from uRole in dbContext.Roles
                            select new { ID = uRole.id, ROLE = uRole.role1 }).ToList();
            this.comBoxRoleG.DataSource = userRoleG; //new BindingSource(getRoles(), null);
            this.comBoxRoleG.DisplayMember = "ROLE";
            this.comBoxRoleG.ValueMember = "ID";

            var userRoleDesG = (from uRole in dbContext.RolesDescriptions
                               select new { ID = uRole.ID, ROLEDES = uRole.Role_Description }).ToList();
            this.comBoxRoleDescG.DataSource = userRoleDesG; //new BindingSource(getRoles(), null);
            this.comBoxRoleDescG.DisplayMember = "ROLEDES";
            this.comBoxRoleDescG.ValueMember = "ID";
            
            string delimeter = " | "; 
            var userG = (from userProfile in dbContext.SecurityUsers
                         select new { ID = userProfile.id, USER = userProfile.MembershipId.Trim() + delimeter + userProfile.Name.Trim() + delimeter + userProfile.FatherName.Trim() }).ToList();

            this.comBoxGur.DataSource = userG; //new BindingSource(getRoles(), null);
            this.comBoxGur.DisplayMember = "USER";
            this.comBoxGur.ValueMember = "ID";

        }

        private void LoadForm()
        {
            

            AssignLanguage();
            this.textBoxID.Text = selectedRecord.Cells["UserId"].Value.ToString().Trim();
            this.textBoxName.Text = selectedRecord.Cells["Name"].Value.ToString().Trim();
            this.textBoxFatherName.Text = selectedRecord.Cells["FatherName"].Value.ToString().Trim();
            this.textBoxAddress.Text = selectedRecord.Cells["PermAddress"].Value.ToString().Trim();
            this.textBoxPresentAddress.Text = selectedRecord.Cells["PresenAddress"].Value.ToString().Trim();
            this.textBoxPhoneNumber.Text = selectedRecord.Cells["PhoneNumber"].Value.ToString().Trim(); 
            this.checkBoxActive.Checked = false;
            this.dateTimePickerDOB.Value = Convert.ToDateTime(selectedRecord.Cells["DOB"].Value.ToString());
            this.dateTimePickerExpiry.Value = Convert.ToDateTime(selectedRecord.Cells["DOE"].Value.ToString());
            this.maskedTextBoxNIC.Text = selectedRecord.Cells["NIC"].Value.ToString().Trim();
            this.textBoxOtherDetails.Text = selectedRecord.Cells["OtherDesc"].Value.ToString().Trim();
            this.textBoxMembership.Text = selectedRecord.Cells["MembershipId"].Value.ToString().Trim();
            

            loadGrid(Convert.ToInt32(selectedRecord.Cells["Id"].Value.ToString()));

            var userRole = (from uRole in dbContext.Roles
                            select new { ID = uRole.id, ROLE = uRole.role1 }).ToList();
            this.comBoxRole.DataSource = userRole; //new BindingSource(getRoles(), null);
            this.comBoxRole.DisplayMember = "ROLE";
            this.comBoxRole.ValueMember = "ID";

            var userRoleDes = (from uRole in dbContext.RolesDescriptions
                               select new { ID = uRole.ID, ROLEDES = uRole.Role_Description }).ToList();
            this.comBoxRoleDesc.DataSource = userRoleDes; //new BindingSource(getRoles(), null);
            this.comBoxRoleDesc.DisplayMember = "ROLEDES";
            this.comBoxRoleDesc.ValueMember = "ID";
          

            var userRoleG = (from uRole in dbContext.Roles
                             select new { ID = uRole.id, ROLE = uRole.role1 }).ToList();
            this.comBoxRoleG.DataSource = userRoleG; //new BindingSource(getRoles(), null);
            this.comBoxRoleG.DisplayMember = "ROLE";
            this.comBoxRoleG.ValueMember = "ID";

            var userRoleDesG = (from uRole in dbContext.RolesDescriptions
                                select new { ID = uRole.ID, ROLEDES = uRole.Role_Description }).ToList();
            this.comBoxRoleDescG.DataSource = userRoleDesG; //new BindingSource(getRoles(), null);
            this.comBoxRoleDescG.DisplayMember = "ROLEDES";
            this.comBoxRoleDescG.ValueMember = "ID";

            string delimeter = " | ";
            var userG = (from userProfile in dbContext.SecurityUsers
                         select new { ID = userProfile.id, USER = userProfile.MembershipId.Trim() + delimeter + userProfile.Name.Trim() + delimeter + userProfile.FatherName.Trim() }).ToList();

            this.comBoxGur.DataSource = userG; 
            this.comBoxGur.DisplayMember = "USER";
            this.comBoxGur.ValueMember = "ID";

            this.comBoxRole.SelectedValue = int.Parse(selectedRecord.Cells["RoleId"].Value.ToString());
            this.comBoxRoleDesc.SelectedValue = int.Parse(selectedRecord.Cells["roleDesId"].Value.ToString());
            

            try
            {                
                byte[] pictureArray = (byte[])selectedRecord.Cells["Photo"].Value;
                                
                MemoryStream ms = new MemoryStream(pictureArray);

                Bitmap img = (Bitmap)Image.FromStream(ms);
                
                img.Save(@"C:\TechxionDB\Photos\user.jpg", ImageFormat.Jpeg);

                this.pictureBoxProfilePic.Image = (Image)img;
            }
            catch(Exception ex) { }

            try
            {
                byte[] thumbPicArray = (byte[])selectedRecord.Cells["ThumbImage"].Value;

                MemoryStream ms = new MemoryStream(thumbPicArray);

                Bitmap img = (Bitmap)Image.FromStream(ms);

                img.Save(@"C:\TechxionDB\Photos\thumb.jpg", ImageFormat.Jpeg);

                this.pictureBoxThumb.Image = (Image)img;
            }
            catch (Exception ex) { }

            this.barcode1.DataToEncode = "TECH" + this.textBoxID.Text;
            this.barcode1.BMPPicture.Save(@"C:\TechxionDB\Photos\BarCode.jpg", ImageFormat.Jpeg);

            this.buttonPrint.Enabled = true;

        }

        private void loadGrid(int userID)
        {

            var selRec = (from g in dbContext.Gurantors
                          join ro in dbContext.Roles on g.RoleID equals ro.id
                          join rd in dbContext.RolesDescriptions on g.RoleDesID equals rd.ID
                          join su in dbContext.SecurityUsers on g.UserID equals su.id
                          join gu in dbContext.SecurityUsers on g.GurantorID equals gu.id
                          where g.UserID == userID
                          select new { GId = g.GurantorID, Gurantor = gu.Name, RoleID = g.RoleID, Role = ro.description, RoleDSID = g.RoleDesID, RoleDS = rd.Role_Description }).ToList();

            dGV.DataSource = selRec;
        }

        private int  generatID()
        {

            try
            {
                var memberID = (from mem in dbContext.SecurityUsers select mem.UserId).Max();

                return ((Convert.ToInt32(memberID) < 20000000) ? 20000000 : Convert.ToInt32(memberID) + 1);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return -1;
        }

      

        private void AssignLanguage()
        {
            int count = InputLanguage.InstalledInputLanguages.Count;
            for (int i = 0; i < count; i++)
            {

                if (InputLanguage.InstalledInputLanguages[i].LayoutName.Contains("Urdu") == true)
                {
                    UrduLanguage = InputLanguage.InstalledInputLanguages[i];

                }
                else if (InputLanguage.InstalledInputLanguages[i].LayoutName.Contains("US") == true)
                {
                    EnglishLanguage = InputLanguage.InstalledInputLanguages[i];

                }
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {

            var images = from p in dbContext.SecurityUsers.AsEnumerable()                          
                         select Image.FromStream(new MemoryStream(p.Photo.ToArray())); 


            foreach (Image image in images)
            {
                
                pictureBox1.Image = image;
            } 
                
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void btnAddtoGrid_Click(object sender, EventArgs e)
        {
            try
            {
                if (dGV.RowCount == 0)
                {
                    dGV.DataSource = setProfile();
                }
                else
                {


                    DataTable table = new DataTable();

                    // Crea las columnas  
                    for (int iCol = 0; iCol < dGV.Columns.Count; iCol++)
                    {
                        table.Columns.Add(dGV.Columns[iCol].Name);
                    }

                    foreach (DataGridViewRow row in dGV.Rows)
                    {
                        DataRow datarw = table.NewRow();
                        for (int iCol = 0; iCol < dGV.Columns.Count; iCol++)
                        {
                            datarw[iCol] = row.Cells[iCol].Value;
                        }
                        table.Rows.Add(datarw);
                    }

                    // dGV.DataSource = setRow((DataTable)dGV.DataSource);
                    dGV.DataSource = setRow(table);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }

        private  DataTable setProfile()
        {


            DataTable dt = new DataTable();
            dt.Columns.Add("GId", typeof(int));
            dt.Columns.Add("Gurantor", typeof(string));
            dt.Columns.Add("RoleID", typeof(int));
            dt.Columns.Add("Role", typeof(string));
            dt.Columns.Add("RoleDSID", typeof(int));
            dt.Columns.Add("RoleDS", typeof(string));

            dt = setRow(dt);
            dt.AcceptChanges();
            return dt;

        }

        private DataTable setRow( DataTable dt)
        {

            //DataTable dt = new DataTable("");
            dt.Rows.Add(comBoxGur.SelectedValue.ToString(), comBoxGur.Text, comBoxRoleG.SelectedValue.ToString(), comBoxRoleG.Text, comBoxRoleDescG.SelectedValue.ToString(), comBoxRoleDescG.Text);
            dt.AcceptChanges();
            return dt;
        }

        private void btnDelfromGrid_Click(object sender, EventArgs e)
        {
            if (dGV.SelectedRows.Count == 1)
            {
               
                DataGridViewRow row = dGV.SelectedRows[0];
                dGV.Rows.Remove(row);
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            Reports.CardReportForm reportForm = new Reports.CardReportForm();
            reportForm.nameUser = this.textBoxName.Text.Trim();

            reportForm.photoImage = @"C:\TechxionDB\Photos\user.jpg";
            reportForm.barCodeImage = @"C:\TechxionDB\Photos\BarCode.jpg";

            reportForm.referenceUser = this.comBoxRole.Text.Trim() + " - " + this.comBoxRoleDesc.Text.Trim();

            reportForm.startDate = DateTime.Today.ToShortDateString();
            reportForm.endDate = this.dateTimePickerExpiry.Value.ToShortDateString();
            reportForm.dateOfBirth = this.dateTimePickerDOB.Value.ToShortDateString();
            
            reportForm.presentAddress = this.textBoxPresentAddress.Text.Trim();
            reportForm.techNumber = this.textBoxMembership.Text.Trim();

            reportForm.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Collections.ArrayList al = new System.Collections.ArrayList();

            foreach (Device device in Device.FindDevices())
                al.Add(device);

            

            if (al.Count == 0)
            {
                MessageBox.Show("No Camera Detected");

                return;
            }

            Device selectedDevice = al[0] as Device;
            
            
            imageCaptureControlCamera.Device = selectedDevice;
            imageCaptureControlCamera.Start();


            this.imageCaptureControlCamera.Visible = true;
        }

        private void buttonNewCard_Click(object sender, EventArgs e)
        {           

                this.textBoxID.Text = generatID().ToString();
            
        }

        private void buttonFinger_Click(object sender, EventArgs e)
        {
            EnrollmentForm Enroller = new EnrollmentForm();
            Enroller.OnTemplate += this.OnTemplate;
            Enroller.ShowDialog();
        }


        private void OnTemplate(DPFP.Template template)
        {
            if (template == null)
            {
                MessageBox.Show("Thumb not enrolled correctly");
            }
            else 
            {
                //thumbImpression = template.Bytes;
                byte[] arr = template.Bytes;
                thumbImpression = template.Serialize(ref arr);

                this.pictureBoxThumb.Image = Image.FromFile(@"C:\TechxionDB\Photos\thumb.jpg");
            } 

            
            
        }

        private void button3_Click(object sender, EventArgs e)
        {

            imageCaptureControlCamera.Stop();
            imageCaptureControlCamera.Device = null;
        }
        
        
      
    
      
    }
}

